/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 15:53:26
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.action.AbsSdkDoAction;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.base.BaseManager;
import cn.cmcc.online.smsapi.sdk.db.entity.MatchCacheManager;
import cn.cmcc.online.smsapi.sdk.db.entity.SceneRule;
import cn.cmcc.online.smsapi.sdk.db.entity.SceneconfigManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.queue.SdkTaskQueue;
import cn.cmcc.online.smsapi.sdk.queue.TaskInfo;
import cn.cmcc.online.smsapi.sdk.service.baseparse.BaseParseService;
import cn.cmcc.online.smsapi.sdk.smsmessage.BusinessSmsMessage;
import cn.cmcc.online.smsapi.sdk.title.SmsTitleManager;
import cn.cmcc.online.smsapi.sdk.ui.popu.util.ViewUtil;
import cn.cmcc.online.smsapi.util.ParseBubbleManager;
import cn.cmcc.online.smsapi.util.ParseRichBubbleManager;
import cn.cmcc.online.smsapi.util.UUIDUtils;

public class PopupUtil {

    public static boolean isPopupAble(Map<String, Object> valueMap, String titleNo) {
    		return true;
    }

    /*SDK-407 hewengao 20160425 start*/
   /**
    * 是否是固话正则
    */
   final static Pattern FIXED_PHONE  = java.util.regex.Pattern.compile("(?<![\\-0-9])0\\d{2,3}-?\\d{7,8}(?!\\d)");
   /*SDK-407 hewengao 20160425 end*/
   
    public static boolean isEnterpriseSms(Context ctx, String phoneNumber, String smsContent, Map<String, String> extend) {
        phoneNumber = StringUtils.getPhoneNumberNo86(phoneNumber);
        if (StringUtils.isNull(phoneNumber)) {
            return false;
        }

        phoneNumber = phoneNumber.replace(" ", "").replace("-", "");

        String allArr[] = { "10088", "10198", "101901", "123662", "12306", "12110110", "121100020", "11888", "11868", "1186666", "118388", "118200", "118114", "118100", "118067", "11803080", "11185", "11183", "13800138000", "095583", "1252004411", "12520", "12520029", "12520035", "125200353", "125200352", "125200304", "125200351", "12520010", "12520021", "125200303", "1252003300000", "12520032", "125200302", "12520028", "12520038", "12520024", "12520036", "125200301", "12520027", "125200354", "1252003300000", "053287003810" };
        int len = allArr.length;

        for (int i = 0; i < len; i++) {
            if (allArr[i].equals(phoneNumber)) {
                return true;
            }
        }
        String[] startArr = { "96", "95", "106", "10178", "10086", "1006", "1001", "1000", "116114" };
        len = startArr.length;
        for (int i = 0; i < len; i++) {
            if (phoneNumber.startsWith(startArr[i])) {
                return true;
            }
        }

        if (phoneNumber.startsWith("12520030") && phoneNumber.length() <= 10) {
            // 开头总长度不超过10
            return true;
        }
        if (phoneNumber.startsWith("12520036") && phoneNumber.length() == 19) {
            // 开头且后面是手机号
            return StringUtils.sj(phoneNumber.replace("12520036", ""));
        }
        /*SDK-418 hewengao 20160428 start*/
        if(extend != null && extend.containsKey("FIXED_PHONE") && !"false".equalsIgnoreCase(extend.get("FIXED_PHONE"))){
            return isFixedPhoneInner(phoneNumber);
        }
        return false;
        /*SDK-418 hewengao 20160428 end*/
    }
    /*SDK-407 hewengao 20160425 start*/
   /**
    * 是否固定电话 
    * @param phoneNumber
    * @return
    */
    public static boolean isFixedPhone(String phoneNumber){
    	try{
            ClassLoader dexClassLoader = DexUtil.getDexClassLoader();
            if (dexClassLoader != null) {
    		    Class onlineParseImplClass = dexClassLoader.loadClass("cn.com.xy.sms.sdk.Iservice.OnlineParseImpl"); 
    		    Method md = onlineParseImplClass.getMethod("isFixedPhone", String.class);
    		    return (Boolean)md.invoke(onlineParseImplClass, phoneNumber);
            }
    	}catch(Throwable e){
    		LogManager.e(Constant.TAG, "PopupUtil.isFixedPhone", e);
    	}
		return isFixedPhoneInner(phoneNumber);
    }
    
    private static boolean isFixedPhoneInner(String phoneNumber){
    	try {
			// 是否是固定电话
			Matcher matcher = FIXED_PHONE.matcher(phoneNumber);
			if (matcher.find()) {
				return true;
			}
		} catch (Throwable e) {
			LogManager.e("xiaoyuan", "FIXED_PHONE: ",e);
		}
		return false;
    }
    /*SDK-407 hewengao 20160425 end*/
    
    public static int getActionCode(String action) {
        int type = -1;
        try {
            if (!StringUtils.isNull(action)) {
                if (action.equalsIgnoreCase("url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("reply_sms")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("reply_sms_fwd")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("call_phone") || "call".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_CALL;
                } else if (action.equalsIgnoreCase("reply_sms_open")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("access_url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("down_url") || "download".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("send_email")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("weibo_url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("map_site") || "open_map".equalsIgnoreCase(action) || "open_map_list".equalsIgnoreCase(action) || "open_map_browser".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_MAP;
                } else if (action.equalsIgnoreCase("chong_zhi") || action.equalsIgnoreCase("recharge") || "zfb_recharge".equalsIgnoreCase(action) || "WEB_CHONG_ZHI".equalsIgnoreCase(action) || "WEB_RECHARGE_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_PAY_CHONGZHI;
                } else if ("repayment".equalsIgnoreCase(action) || "zfb_repayment".equals(action) || "WEB_REPAYMENT".equalsIgnoreCase(action) || "WEB_REPAYMENT_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_PAY_HUANKUAN;
                } else if (action.equalsIgnoreCase("copy_code")) {
                    type = Constant.ACTION_COPY_CODE;
                } else if ("open_app".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_OPEN_APP;
                } else if ("time_remind".equalsIgnoreCase(action) || "sdk_time_remind".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_DATE_REMIND;
                } else if ("pay_water_gas".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_WATER_GAS;
                } else if ("WEB_TRAFFIC_ORDER".equalsIgnoreCase(action) || "WEB_TRAFFIC_CHOOSE".equalsIgnoreCase(action) || "WEB_PURCHASE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_TRAFFIC_ORDER;
                } else if ("WEB_QUERY_EXPRESS_FLOW".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_EXPRESS_FLOW;
                } else if ("WEB_QUERY_FLIGHT_TREND".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_FLIGHT_TREND;
                } else if ("WEB_INSTALMENT_PLAN".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_INSTALMENT_PLAN;
                } else if ("WEB_TRAIN_STATION".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_TRAIN_STATION;
                } else if ("WEB_NEAR_SITE".equalsIgnoreCase(action) || "near_site".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_NEAR_SITE;
                } else if ("WEB_LIVE_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_LIVE_SERVER;
                } else {
                    type = Constant.ACTION_OTHER;
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
            LogManager.e("XIAOYUAN", "PopupUtil getActionCode error: ", e);
        }

        return type;
    }

    /*SDK-473 hewengao 20160603 start */
    /**
     * 启动web Activity
     * 
     * @param context
     * @param jsobj
     * @param actionType
     */
	public static boolean startWebActivity(Context context, JSONObject jsobj,
			String actionType, String phoneNum) {
		return AbsSdkDoAction.openStartWebActivity(context, jsobj, actionType, phoneNum, null);
	}
	 /*SDK-473 hewengao 20160603 end */

    /**
     * 算法解析的结果封装成,短信到会话卡片需要的结果
     * 
     * @param context
     * @param msgId
     *            短消息ID
     * @param phoneNumber
     *            短信接入码,短信发送方号码
     * @param smsCenterNum
     *            短信发送方,短信中心号码
     * @param smsContent
     *            短信内容
     * @param smsReceiveTime
     *            短信接收时间
     * @param returnCacheType
     *            返回数据的缓存类型 1:返回SDK缓存标识 2:返回SDK识别结果 由开发者保存sdk标识或识别结果.
     * @param valueMap
     *            识别算法分析的结果
     * @return Map<String,Object> 包含key CACHE_SDK_MSG_ID 识别结果标识ID
     *         returnCacheType=1时 CACHE_SDK_MSG_RESULT:识别结果 value:jsonstring
     *         returnCacheType=2时
     * @throws Throwable
     */

    public static Map<String, Object> parseMsgToBubbleCardResult(Context context, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, Object> valueMap, boolean resultAddToMemory) throws Exception {
        try {
            // LogManager.d("BubbleCardResult", "valueMap: "+valueMap);
            if (valueMap == null) {
                LogManager.e("xiaoyuan_test", "valueMap null .msgId:  ", null);
                return null;
            }
            // LogManager.e("BubbleCardResult",
            // "valueMap success. msgId: "+msgId);
            valueMap.remove("viewPartParam");
            long start = System.currentTimeMillis();
            Map<String, Object> res = DexUtil.handerBubbleValueMap(valueMap);
            // LogManager.d("BubbleCardResult", "valueMap handerValueMap="+res);
            long end = System.currentTimeMillis();
//            LogManager.d("xiaoyuan_test", "handerBubbleValueMap time:" + (end - start));

            long bubbleLasttime = System.currentTimeMillis();
            int parseStatu = 0;
            if (res != null) {
                if (valueMap.containsKey(Constant.KEY_IS_SAFE_VERIFY_CODE)) {
                    res.put(Constant.KEY_IS_SAFE_VERIFY_CODE, String.valueOf(valueMap.get(Constant.KEY_IS_SAFE_VERIFY_CODE)));
                }

                // LogManager.d("BubbleCardResult",
                // "valueMap handerValueMap success. ");
                // 此处check是否能正常显示汽泡视图,并同时需要检测汽泡所需的要配置数据是否正常.将配置数据一并,加入返回的数据中.
                String titleNo = (String) res.get("title_num");
                // LogManager.e("BubbleCardResult",
                // "valueMap res success. .msgId:  "+msgId+" titleNo: "+titleNo);
                // PrintTestLogUtil.printTestLog("parseMsgToBubbleCardResult",
                // "titleNo="+titleNo);
                HashMap<String, String> bubleSmsTitle = SmsTitleManager.getBubleSmsTitle(titleNo);
                end = System.currentTimeMillis();
//                LogManager.d("xiaoyuan_test", "getBubleSmsTitle time:" + (end - start));
                // PrintTestLogUtil.printTestLog("parseMsgToBubbleCardResult",
                // "BubleSmsTitle="+BubleSmsTitle);

                boolean bubleSmsTitleIsNotNull = bubleSmsTitle != null && !bubleSmsTitle.isEmpty();
                    if (bubleSmsTitleIsNotNull) {
                        res.putAll(bubleSmsTitle);
                    }
                    if (isPopupAble(res, titleNo)) {// 表示汽泡视图准备就绪,可能提供给开发者使用
                        phoneNumber = StringUtils.getPhoneNumberNo86(phoneNumber);
                        /* SDK-647 likuangkuang 20161104 start if remote call, it is necessary to get JSONObject using the default constructor */
                        res.remove("viewPartParam");
                        JSONObject jsobj = new JSONObject(res);
                        /* SDK-647 likuangkuang 20161104 end */

                        long sdkMsgId = 0;
                        // 此处需要将json string入库至sdk缓存,并返回SDK_MSG_ID 返回给开发者缓存

                        String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
                        MatchCacheManager.removeUselessKey(jsobj);
                        if (!StringUtils.isNull(msg_num_md5)) {
                            ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", phoneNumber, "scene_id", titleNo, "msg_id", msgId, "bubble_result", jsobj.toString(), "save_time", String.valueOf(smsReceiveTime), "bubble_lasttime", String.valueOf(System.currentTimeMillis()), "urls", jsobj.optString(Constant.URLS));

                            sdkMsgId = MatchCacheManager.insertOrUpdate(matchCache, 2);
                            /* SDK-559 huangzhiqiang 20160725 start */
                            LogManager.d("xiaoyuan_test", "MatchCacheManager insertOrUpdate sdkMsgId:", String.valueOf(sdkMsgId));
                            /* SDK-559 huangzhiqiang 20160725 end */
                        }
                        res.clear();
                        if (returnCacheType == 1) {

                            res.put("CACHE_SDK_MSG_ID", sdkMsgId);
                            // res.put("View_fdes",
                            // JsonUtil.getValueFromJsonObject(jsobj,
                            // "View_fdes"));
                        } else {
                            // res.clear();
                            // 返回jsonString给开发者,并由开发者自行缓存
                            res.put("CACHE_SDK_MSG_RESULT", jsobj.toString());
                            // res.put("View_fdes",
                            // JsonUtil.getValueFromJsonObject(jsobj,
                            // "View_fdes"));
                        }
                        res.put("View_fdes", JsonUtil.getValueFromJsonObject(jsobj, "View_fdes"));

                        // if(resultAddToMemory &&
                        // ParseBubbleManager.equalPhoneNum(phoneNumber)){
                        // LogManager.e("duoqu_test",
                        // "resultAddToMemory ParseBubbleManager.equalPhoneNum addEffectiveBubbleData msgId:"+msgId);
                        if (resultAddToMemory) {
                            ParseRichBubbleManager.addEffectiveBubbleData(phoneNumber, msgId, jsobj);
                        }
                        res.put("BUBBLE_JSON_RESULT", jsobj);
                        res.put("parseStatu", 1);
                        // end = System.currentTimeMillis();
                        // LogManager.d("duoqu_test",
                        // "MatchCacheManager.insertOrUpdate time:"+(end-start));
                        return res;
                    } else {
                        /*SDK-674 hewengao 20161114 start*/
                        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," parseMsgToBubbleCardResult  isPopupAble is faild",null);
                        /*SDK-674 hewengao 20161114 end*/
                        LogManager.d("xiaoyuan_test", "valueMap isPopupAble faild.msgId: ", msgId);
                        // isPopupAble faild
                        parseStatu = -3;
                    }


                // 脚本已识别但是找不到资源的情况下，查询tb_match_cache是否已存在对应数据，
                // 无数据则代表是第一次进行识别，将最后识别时间提前5小时58分钟，使短信在2分钟后重新进行识别
                // 已经存在数据代表2分钟后识别仍然没有找到资源，则在7分钟后重新识别
                if (MatchCacheManager.queryDataCount(msgId, MatchCacheManager.getMD5(phoneNumber, smsContent)) == 0) {
                    bubbleLasttime = System.currentTimeMillis() - (DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, 6 * 3600 * 1000L) - 120000L);// 2分钟
//                    LogManager.e("xiaoyuan_test", "脚本已识别但是找不到资源valueMap res faild.msgId: " + msgId + "bubbleLasttime=" + bubbleLasttime + "time=" + new java.util.Date(bubbleLasttime).toLocaleString(), null);
                } else {
                    bubbleLasttime = System.currentTimeMillis() - (DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, 6 * 3600 * 1000L) - 420000L);// 7分钟
//                    LogManager.e("xiaoyuan_test", "脚本已识别隔2分钟后仍然查不到资源valueMap res faild.msgId: " + msgId + "bubbleLasttime=" + bubbleLasttime, null);
                }
                // end = System.currentTimeMillis();
                // LogManager.d("duoqu_test",
                // "MatchCacheManager.queryDataCount time:"+(end-start));
            } else {
                /*SDK-674 hewengao 20161114 start*/
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," parseMsgToBubbleCardResult is null",null);
                /*SDK-674 hewengao 20161114 end*/
                LogManager.d("xiaoyuan_test", "valueMap res faild.msgId: ",msgId);
            }
            String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
            if (!StringUtils.isNull(msg_num_md5)) {// 不能处理的也需要加入缓存.
                ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", StringUtils.getPhoneNumberNo86(phoneNumber), "scene_id", "", "msg_id", msgId, "bubble_result", "", "save_time", String.valueOf(smsReceiveTime), "bubble_lasttime", String.valueOf(bubbleLasttime));
                MatchCacheManager.insertOrUpdate(matchCache, 2);
            }
            // if(resultAddToMemory &&
            // ParseBubbleManager.equalPhoneNum(phoneNumber)){
            if (resultAddToMemory) {
                ParseRichBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
            }
            // end = System.currentTimeMillis();
            // LogManager.d("duoqu_test",
            // "MatchCacheManager.last  @@@@@  time:"+(end-start));
            if (parseStatu != 0 && res != null) {
                res.clear();
                res.put("parseStatu", parseStatu);
                return res;
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "parseMsgToBubbleCardResult: ", e);

        } finally {
            // 触发情景check队列，情景down队列，资源down队列
            SceneconfigDownloaderQueue.runSceneconfigDownloadQueue();
        }
        return null;
    }

    /**
     * 算法解析的结果封装成,短信到会话卡片需要的结果
     * 
     * @param context
     * @param msgId
     *            短消息ID
     * @param phoneNumber
     *            短信接入码,短信发送方号码
     * @param smsCenterNum
     *            短信发送方,短信中心号码
     * @param smsContent
     *            短信内容
     * @param smsReceiveTime
     *            短信接收时间
     * @param returnCacheType
     *            返回数据的缓存类型 1:返回SDK缓存标识 2:返回SDK识别结果 由开发者保存sdk标识或识别结果.
     * @param valueMap
     *            识别算法分析的结果
     * @return Map<String,Object> 包含key CACHE_SDK_MSG_ID 识别结果标识ID
     *         returnCacheType=1时 CACHE_SDK_MSG_RESULT:识别结果 value:jsonstring
     *         returnCacheType=2时
     * @throws Throwable
     */

    public static Map<String, Object> parseMsgToSimpleBubbleResult(Context context, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, Object> valueMap, boolean resultAddMemory,Map<String, String> extend) throws Exception {
        if (valueMap == null) {
            return null;
        }
//        String data = (String) valueMap.get("ADACTION");
        String data = BaseParseService.getAdAction(valueMap, extend);
        Map<String, Object> res = null;
        if (returnCacheType == 1) {// xiao yuan sdk persistent simple bubble
                                   // data
            long sdkMsgId = -1;
            String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
            if (!StringUtils.isNull(msg_num_md5)) {

                ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", StringUtils.getPhoneNumberNo86(phoneNumber), "msg_id", msgId, "session_reuslt", data == null ? "" : data, "save_time", String.valueOf(smsReceiveTime), "session_lasttime", String.valueOf(System.currentTimeMillis()));
                sdkMsgId = MatchCacheManager.insertOrUpdate(matchCache, 1);
            }
            if (data != null) {
                res = new HashMap<String, Object>();
                res.put("CACHE_SDK_MSG_ID", sdkMsgId);
                res.put("CACHE_SDK_MSG_SIMPLE_RESULT", data);
            }
        } else {
            if (data != null) {
                res = new HashMap<String, Object>();
                res.put("CACHE_SDK_MSG_SIMPLE_RESULT", data);
            }
        }
        if (resultAddMemory && ParseBubbleManager.equalPhoneNum(phoneNumber)) {
            try {
                if (data != null) {
                    JSONArray simpleArrData = new JSONArray(data);
                    ParseBubbleManager.addEffectiveBubbleData(phoneNumber, msgId, simpleArrData);
                } else {
                    ParseBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
                }
            } catch (Throwable e) {
                ParseBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
                // e.printStackTrace();
                LogManager.e(Constant.TAG, "parseMsgToSimpleBubbleResult: ", e);

            }

        }
        return res;
    }

    public static String getValue() {
        try {
            /* SDK-570 huangzhiqiang 20160802 start */
            String res = AppUtil.assemble();
            res = StringUtils.handlerAssemble(res);
            /* SDK-570 huangzhiqiang 20160802 end */
            return StringUtils.decode(res);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PopupUtil getValue error", e);
        }
        return "";
    }
}
